<template>
  <div class="ui-field-latlng" v-loading="loading">
    <div class="map"></div>
    <div class="info" v-show="!loading">
      <div class="input-item searchbox">
        <div class="input-item-prepend">
          <span class="input-item-text">搜索关键字</span>
        </div>
        <!--    form="__ignore__" 避免 enter提交表单    -->
        <input ref="input" type="text" form="__ignore__" placeholder="请输入...">
        <div ref="output" class="search-result"></div>
      </div>
    </div>
  </div>
</template>

<script>
  import gcoord from 'gcoord';
  import {getAMap} from '../../config/amap';
  import {FieldMixin} from '@v2coding/ui';

  const CoordTypes = {
    bd09: gcoord.BD09,
    gcj02: gcoord.GCJ02,
    wgs84: gcoord.WGS84,
  };

  export default {
    name: 'ui-field-latlng',
    mixins: [FieldMixin],
    props: {
      coordType: {
        type: String,
        default: 'wgs84',
        validator: (val) => Object.keys(CoordTypes).includes(val),
      },
    },
    data() {
      return {
        loading: true,
        keyword: '',
      };
    },
    computed: {
      point() {
        if (!this.value) {
          return null;
        }
        if (!this.isValidPoint(this.value)) {
          return null;
        }
        const [lat, lng] = this.value.split(',');
        return {lat: +lat, lng: +lng};
      },
    },
    watch: {
      point(p) {
        this.onPointChange(p);
      },
    },
    methods: {
      init() {
        getAMap(['AMap.ToolBar', 'AMap.Geolocation', 'AMap.AutoComplete']).then((AMap) => {
          this.initMap(AMap);
          this.loading = false;
          this.done();
        });
      },
      initMap(AMap) {
        const map = new AMap.Map(this.$el.querySelector('.map'), {
          zoom: 11,
        });

        map.addControl(new AMap.ToolBar({position: 'RT'}));
        map.addControl(new AMap.Geolocation({position: 'RB'}));
        const auto = new AMap.AutoComplete({
          input: this.$refs.input,
          output: this.$refs.output,
        });

        map.on('click', this.onMapClick);
        auto.on('select', (event) => {
          if (!event.poi || !event.poi.location) {
            return;
          }
          map.setZoomAndCenter(16, event.poi.location);
        });

        this.map = map;

        this.onPointChange(this.point);
      },
      isValidPoint(val) {
        const [lat, lng] = val.split(',');
        return !(isNaN(+lat) || isNaN(+lng));
      },
      onMapClick({lnglat}) {
        let {lat, lng} = lnglat;
        // 当前地图是 GCJ02 坐标系
        if (this.coordType !== 'gcj02') {
          [lng, lat] = gcoord.transform([lng, lat], gcoord.GCJ02, CoordTypes[this.coordType]);
          lng = lng.toFixed(7) / 1;
          lat = lat.toFixed(7) / 1;
        }
        this.onChange([lat, lng].join(','));
      },
      onPointChange(point) {
        if (!this.map) {
          return;
        }
        this.map.clearMap();
        if (!point) {
          return;
        }
        let {lng, lat} = point;
        // 当前地图是 GCJ02 坐标系
        if (this.coordType !== 'gcj02') {
          [lng, lat] = gcoord.transform([lng, lat], CoordTypes[this.coordType], gcoord.GCJ02);
        }
        // eslint-disable-next-line no-undef
        const marker = new AMap.Marker({position: new AMap.LngLat(lng, lat)});
        this.map.add(marker);
        this.map.setCenter([lng, lat]);
      },
    },
  };
</script>

<style lang="less">
  .ui-field-latlng {
    width: 100%;
    height: 280px;
    position: relative;

    .map {
      width: 100%;
      height: 100%;
    }

    .info {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      pointer-events: none;

      .searchbox {
        left: 12px;
        top: 12px;
        background-color: #fff;
        box-shadow: 0 0 3px rgba(0, 0, 0, .5);
        pointer-events: initial;
        border-radius: 3px;
        padding: 3px;

        .search-result {
          position: absolute;
          top: calc(100% - 2px);
          left: 0;
          right: 0;
          background-color: #fefefe;
          box-shadow: 0 1px 3px #999 ;
          visibility: hidden;
          border-radius: 0 0 3px 3px;

          .auto-item {
            white-space: nowrap;
            font-size: 12px;
            cursor: pointer;
            padding: 4px;
            line-height: 14px;
          }
        }
      }
    }

    .input-item {
      position: relative;
      display: inline-flex;
      align-items: center;
      width: 220px;
      font-size: 12px;

      .input-item-prepend {
        margin-right: -1px;

        .input-item-text {
          padding: 0.25em 0.5em;
          display: block;
          text-justify: distribute-all-lines;
          text-align-last: justify;
          align-items: center;
          margin-bottom: 0;
          font-weight: 400;
          line-height: 1.5;
          color: #495057;
          text-align: center;
          white-space: nowrap;
          background-color: #e9ecef;
          border: 1px solid #ced4da;
          border-radius: .25rem 0 0 .25rem;
          box-sizing: border-box;
        }
      }

      input {
        position: relative;
        flex: 1 1 auto;
        width: 1%;
        margin: 0;
        background: #fff;
        padding: 0.25em 0.5em;
        display: inline-block;
        line-height: 1.5;
        color: #495057;
        vertical-align: middle;
        border: 1px solid #ced4da;
        border-radius: 0 .25rem .25rem 0;
        appearance: none;
        box-sizing: border-box;

        &:focus {
          border-color: #80bdff;
          outline: 0;
          box-shadow: 0 0 0 0.1rem rgba(128, 189, 255, .1);
        }
      }
    }

    .amap-logo,
    .amap-copyright {
      display: none !important;
    }
  }
</style>
